/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAPatronLoansViewController.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 27/08/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAPatronLoansViewController.h"
#import "BAUtils.h"
#import "BALoanCell.h"
#import "BARenewLoansViewController.h"
#import "BALoginViewController.h"
#import "BALibrarySettings.h"


@interface BAPatronLoansViewController ()

@property (strong, nonatomic) NSMutableArray* loans;
@end

@implementation BAPatronLoansViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    if (RD_IS_IPAD) {
        self.renewAllLoansButton.titleLabel.font = BA_FONT_REGULAR(11);
    } else {
        BA_LABEL_SET_FONT_REGULAR(self.renewAllLoansButton.titleLabel);
    }
    
    //[self.renewAllLoansButton.titleLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:80.0/255.0 blue:0.0 alpha:1]];
//    [self refreshLoansList];

    [self setupCustomerColors:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupCustomerColors:) name:BA_LIBRARY_SETTINGS_OBJECT_CHANGED object:nil];
    
    self.renewAllLoansButton.hidden = YES;
    self.renewAllLoansButtonHeightConstraint.constant = 0;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)setupCustomerColors:(id)sender
{
    [self.renewAllLoansButton setTitleColor:[[BALibrarySettings instance] getCustomerColorNormal] forState:UIControlStateNormal];
    [self.renewAllLoansButton setTitleColor:[[BALibrarySettings instance] getCustomerColorNormal] forState:UIControlStateNormal];
}

-(void)dealloc
{
    [BARPCManager closeConnectionsForView:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_LIBRARY_SETTINGS_OBJECT_CHANGED object:nil];
}

-(void)initiateRefreshLoans
{
    self.loans = [NSMutableArray new];
    [self.tableView reloadData];
    [self.loadingIndicator startAnimating];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:BA_LOANS_LIST_NEEDS_REFRESH_NOW object:nil];
}

- (void)refreshLoansList:(NSMutableArray*)list
{
    self.loans = list;
    
    [self.tableView reloadData];
    [self.loadingIndicator stopAnimating];
    if ([self.loans count] > 0) {
        self.renewAllLoansButtonHeightConstraint.constant = 41;
        self.renewAllLoansButton.hidden = NO;
    }
    else {
        self.renewAllLoansButtonHeightConstraint.constant = 0;
        self.renewAllLoansButton.hidden = YES;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.loans.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BALoanCell* cell = [tableView dequeueReusableCellWithIdentifier:@"LoansListCell"];
    if(cell == nil){
        if (RD_IS_IPAD) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BALoanCell_iPad" owner:self options:nil] objectAtIndex:0];
        } else {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BALoanCell_iPhone" owner:self options:nil] objectAtIndex:0];
        }
        cell.parentLoansViewController = self;
    }
    if(indexPath.item % 2 == 0) {
        [cell.contentView setBackgroundColor:[UIColor colorWithRed:241.0/255.0 green:241.0/255.0 blue:241.0/255.0 alpha:1]];
    } else {
        [cell.contentView setBackgroundColor:[UIColor colorWithRed:227.0/255.0 green:227.0/255.0 blue:227.0/255.0 alpha:1]];
    }
    
    if(indexPath.row == 0) {
        [cell.leftImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_1"]];
    } else if (indexPath.row == 1) {
        [cell.leftImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_2"]];
    } else if (indexPath.row == 2) {
        [cell.leftImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_3"]];
    } else if (indexPath.row == 3) {
        [cell.leftImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_4"]];
    } else {
        [cell.leftImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_5"]];
    }

    //DLog(@"%f", cell.leftImageView.bounds.origin.x);

    
    BALoan* theloan = [self.loans objectAtIndex:indexPath.row];
    
    [cell setLoan:theloan];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return RD_IS_IPAD ? 100 : 70;
}

-(void)renewLoan:(BALoan *)loanToRenew
{
    DLog(@"renew loan %@",loanToRenew.renewLoanId);
    
    loanToRenew.renewLoanRpcPending = YES;
    
    [BALoginViewController checkLoginStatusFromViewController:self
                                                  resultBlock:^{
                                                      [BARPCManager renewLoansAsyncFromView:self
                                                                                    loanIds:@[loanToRenew.renewLoanId]
                                                                                resultBlock:^(NSDictionary *result) {
                                                                                    for (NSString* key in [result allKeys]) {
                                                                                        BAStandardResultObject* stdresult = [result objectForKey:key];
                                                                                        if (stdresult.result) {
                                                                                            BALoan* updated_loan = stdresult.parsedData;
                                                                                            int found_index = -1;
                                                                                            for (int i=0; i<[self.loans count]; i++) {
                                                                                                BALoan* oldloan = [self.loans objectAtIndex:i];
                                                                                                if ([oldloan.renewLoanId isEqualToString:updated_loan.renewLoanId]) {
                                                                                                    [self.loans replaceObjectAtIndex:i withObject:updated_loan];
                                                                                                    DLog(@"updated old loan idx %d  due %d  with due %d ", i, oldloan.loanDueDate, updated_loan.loanDueDate)
                                                                                                    found_index = i;
                                                                                                }
                                                                                            }
                                                                                            if (found_index==-1) {
                                                                                                //old loan not found, so update entire list
                                                                                                [self initiateRefreshLoans];
                                                                                            } else {
                                                                                                [self.tableView reloadData];
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                       
                                                                                 errorBlock:^(int errorCode, NSString *errorMessage) {
                                                                                     loanToRenew.renewLoanRpcPending = NO;
                                                                                     [self.tableView reloadData];

                                                                                     UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Kunne ikke forny dit lån"
                                                                                                                                     message:errorMessage
                                                                                                                                    delegate:nil
                                                                                                                           cancelButtonTitle:@"OK"
                                                                                                                           otherButtonTitles:nil];
                                                                                     [alert show];
                                                                                 }];
                                                  } errorBlock:^(int errorCode, NSString *errorMessage) {
                                                      // Authentication error.
                                                      loanToRenew.renewLoanRpcPending = NO;
                                                      [self.tableView reloadData];
                                                      
                                                      //don't show alert here, it is already presented by BALoginViewController
                                                  }];
    }

- (IBAction)renewAllLoansClicked:(id)sender {
    [BARenewLoansViewController createRenewAllLoansDialogFromViewController:self];
}

@end
